package com.qf.cx.simplenms.tagmemory.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qf.cx.simplenms.tagmemory.api.TagMemoryManager;
import com.qf.cx.simplenms.tagmemory.model.TagMemoryModel;

public class TagMemoryManagerImpl implements TagMemoryManager {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private Map<String, TagMemoryModel> map = new HashMap<>();

	@Override
	public synchronized TagMemoryModel getTagMemory(String name) {
		TagMemoryModel tagMemory = map.get(name);
		if (tagMemory == null) {
			logger.warn("no tag memory named '{}'", name);
		}
		return tagMemory;
	}

	@Override
	public synchronized void updateCache(List<TagMemoryModel> list) {
		for (Iterator<TagMemoryModel> it = map.values().iterator(); it.hasNext();) {
			TagMemoryModel tm = it.next();
			if (!list.contains(tm)) {
				it.remove();
				logger.debug("delete tag memory {}", tm);
			}
		}

		for (TagMemoryModel t : list) {
			TagMemoryModel previous = map.put(t.name, t);
			if (logger.isDebugEnabled()) {
				if (previous == null) {
					logger.debug("add tag memory {}", t);
				} else {
					logger.debug("update tag memory {}", t);
				}
			}
		}
	}

	@Override
	public String dump() {
		StringBuilder sb = new StringBuilder();
		sb.append("<h1>tagmemories</h1></br>");
		for (Entry<String, TagMemoryModel> entry : map.entrySet()) {
			sb.append(entry.getKey()).append("</br>").append(entry.getValue())
			        .append("</br>");
		}
		sb.append("</br>");
		return sb.toString();
	}

}
